package top.haichi.webpaper.filter;

import lombok.extern.java.Log;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import top.haichi.webpaper.utils.ContentCachingRequestWrapper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@Log
@WebFilter(filterName = "test", urlPatterns = "/*")
public class SignValidateFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String contentType = request.getContentType();
        log.info("request.getContentType()) = " + contentType);
        if (contentType==null){
            chain.doFilter(request, response);
            return;
        }
        if (!contentType.equals("application/json") ) {
            chain.doFilter(request, response);
            return;
        }
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
        String body = IOUtils.toString(requestWrapper.getBody(), request.getCharacterEncoding());
        chain.doFilter(requestWrapper, response);
        return;
    }

    @Override
    public void destroy() {

    }
}
